<?php

class Mac_Db_Clause_Where
{
    private $clauses = array();

    public static function clauses ($left_op, $operator, $right_op = null, $keepRaw = false)
    {
        $clause = new self();
        $clause->andWhere($left_op, $operator, $right_op, $keepRaw);
        return $clause;
    }

    public function andWhere($left_op, $operator, $right_op = null, $keepRaw = false)
    {
        if (($keepRaw === false) && ($right_op !== null)) {
            if (is_array($right_op)) {
                array_walk($right_op, function(&$value, $key) {
                    $value = Mac_Db_Helper::prepareValue($value);
                });
            } else {
                $right_op = Mac_Db_Helper::prepareValue($right_op);
            }
        }

        if (($operator === Mac_Db_Type_Op::IS_NULL) || ($operator === Mac_Db_Type_Op::IS_NOT_NULL)) {
            $this->clauses[] = $left_op.' '.$operator;
        } else if ($operator === Mac_Db_Type_Op::BETWEEN) {
            if (!is_array($right_op) || (sizeof($right_op) != 2)) {
                throw new Mac_Db_Exception_Query_Select_BetweenOperator('BETWEEN clause expecting array with 2 elements as right operand');
            }
            $this->clauses[] = $left_op.' '.$operator.' '.$right_op[0].' AND '.$right_op[1];
        } else if (($operator === Mac_Db_Type_Op::IN) || ($operator === Mac_Db_Type_Op::NOT_IN)) {
            if (!is_array($right_op)) {
                throw new Mac_Db_Exception_Query_Select_InOperator($operator.' clause expecting array as right operand');
            }
            $this->clauses[] = $left_op.' '.$operator.' ('.implode(', ', $right_op).')';
        } else {
            $this->clauses[] = $left_op.' '.$operator.' '.$right_op;
        }
        
        return $this;
    }
    
    public function __toString()
    {
        return implode(' AND ', $this->clauses);
    }
}